# 物品服务层，处理与物品相关的业务逻辑
from models import Item
from extensions import db


def get_all_items():
    return Item.query.all()

def get_item_by_id(item_id):
    return Item.query.get(item_id)

def create_item(name, description, price, user_id, category=None, stock=0, status='在售'):
    new_item = Item(
        name=name, 
        description=description, 
        price=price, 
        user_id=user_id,
        category=category,
        stock=stock,
        status=status
    )
    db.session.add(new_item)
    db.session.commit()
    return new_item

def update_item(item_id, name=None, description=None, price=None, category=None, stock=None, status=None):
    item = get_item_by_id(item_id)
    if not item:
        return None
    
    if name:
        item.name = name
    if description:
        item.description = description
    if price:
        item.price = price
    if category:
        item.category = category
    if stock is not None:
        item.stock = stock
    if status:
        item.status = status
    
    db.session.commit()
    return item

def delete_item(item_id):
    item = get_item_by_id(item_id)
    if not item:
        return False
    
    db.session.delete(item)
    db.session.commit()
    return True